/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package com.nhc.model;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.widget.Toast;

import com.astrob.activitys.AppContext;
import com.astrob.model.LonLat;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.MapViewS;
import com.iflytek.tts.TtsService.TtsSpeaker;

import org.mapsforge.core.util.MercatorProjection;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.model.DisplayModel;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.TileSystem;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;

import zuo.biao.library.base.BaseModel;

public class PaomaoInfo extends BaseModel {

    private static final long serialVersionUID = 1L;

    //地图设置
    private static String PAOMAOSETINFO = "paomao";

    private static String PAOMAOSET_RANGES = "paomao_ranges";//抛锚警告范围
    private static String PAOMAOSET_LON = "paomao_lon";//抛锚位置 lon
    private static String PAOMAOSET_LAT = "paomao_lat";//抛锚位置 lat
    private static String PAOMAOSET_USED = "paomao_used";//激活

    private LonLat ll = new LonLat();
    private boolean paomao_used = false;//激活
    private double paomao_range = 30;//米

    private static PaomaoInfo instance = new PaomaoInfo();

    public static PaomaoInfo getInstance() {
        return instance;
    }

    /**
     * 默认构造方法，JSON等解析时必须要有
     */
    public PaomaoInfo() {
        //default
    }

    public void save(Context context) {
        if (context == null) {
            return;
        }

        SharedPreferences sp = context.getSharedPreferences(
                PAOMAOSETINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(PAOMAOSET_RANGES, this.paomao_range + "");
        editor.putBoolean(PAOMAOSET_USED, this.paomao_used);
        editor.putFloat(PAOMAOSET_LON, (float) ll.GetLon());
        editor.putFloat(PAOMAOSET_LAT, (float) ll.GetLat());
        editor.commit();
    }

    public void load(Context context) {
        if (context == null) {
            return;
        }
        SharedPreferences sp = context.getSharedPreferences(
                PAOMAOSETINFO, Context.MODE_PRIVATE);
        this.paomao_range = Double.valueOf(sp.getString(PAOMAOSET_RANGES, this.paomao_range + ""));
        this.paomao_used = sp.getBoolean(PAOMAOSET_USED, this.paomao_used);
        double lon = (double) sp.getFloat(PAOMAOSET_LON, 0.0f);
        double lat = (double) sp.getFloat(PAOMAOSET_LAT, 0.0f);
        ll = new LonLat(lon, lat);
    }

    public void reset() {
        paomao_used = false;
        paomao_range = 30;
    }

    public LonLat getLl() {
        return ll;
    }

    public void setLl(LonLat ll) {
        this.ll = ll;
    }

    public boolean isPaomao_used() {
        return paomao_used;
    }

    public void setPaomao_used(boolean paomao_used) {
        this.paomao_used = paomao_used;
        if (paomao_used) {
            ll = SysUtils.getInstance().getLL();
        }
    }

    public double getPaomao_range() {
        return paomao_range;
    }

    public void setPaomao_range(double paomao_range) {
        this.paomao_range = paomao_range;
    }

    @Override
    protected boolean isCorrect() {//根据自己的需求决定，也可以直接 return true
        return id > 0;// && StringUtil.isNotEmpty(phone, true);
    }

    int alarmNum = 0;//最多1分钟播报一次

    public void alarm(Context context) {
        if (!paomao_used || ll == null || ll.IsInvalid()) {
            return;
        }

        LonLat carLL = SysUtils.getInstance().getLL();
        double distance = Start.getInstance().MapKit().getDistance(ll, carLL);
        if (distance < paomao_range) {
            alarmNum = -1;
            return;
        }

        if (alarmNum > 60) {
            alarmNum = 0;
        }

        if (alarmNum == 0) {
            TtsSpeaker.getInstance().talk(context.getString(R.string.nylksddpmqy));
            Toast.makeText(context, context.getString(R.string.nylksddpmqy), Toast.LENGTH_LONG).show();
        } else if (alarmNum % 6 == 0) {
//            Utils.playWavFile(Start.RUNDIR + "notify.wav");
            if (mContext != null) {
                MediaPlayer mediaPlayer01;
                mediaPlayer01 = MediaPlayer.create(mContext, R.raw.notify);
                mediaPlayer01.start();
            }
        }

        alarmNum++;

    }

    Context mContext = null;

    public void draw(Context context, Canvas canvas, float ws, MapViewS mapView) {
        if (mContext == null) {
            mContext = context;
        }
        if (!paomao_used || ll == null || ll.IsInvalid()) {
            return;
        }

        if (mapView == null) {
            return;
        }

        LonLat llA = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());//Utils GPS to 火星坐标

        if (!mapView.isInMapRegion(llA)) {
            return;
        }

        Point e = Start.getInstance().MapKit().LL2XY(llA);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        if (SysUtils.getInstance().is240x320) {
            paint.setTextSize(16);
        } else {
            paint.setFakeBoldText(true);
            paint.setStrokeWidth(2);
            paint.setTextSize(40);
        }
        paint.setTypeface(AppContext.getInstances().getIconfont());
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        int range = (int) (Start.getInstance().MapKit().meterDis2Pix((int) paomao_range, mapView._mapWidth) * ws);
        paint.setColor(Color.parseColor("#A066FC66"));
        canvas.drawCircle(e.x * ws, e.y * ws, range, paint);

        paint.setColor(Color.parseColor("#FFFF0000"));
        String iconT = context.getString(R.string.fonticon_more_paomao);
        Rect rect = new Rect();
        paint.getTextBounds(iconT, 0, 1, rect);
        canvas.drawText(iconT, e.x * ws - rect.width() / 2, e.y * ws, paint);

    }

    public void draw2(Context context, Canvas canvas, MapView mapView, boolean isgcj02) {
        if (mContext == null) {
            mContext = context;
        }
        if (!paomao_used || ll == null || ll.IsInvalid()) {
            return;
        }

        if (mapView == null) {
            return;
        }

        LonLat llA = new LonLat(ll.GetLon(), ll.GetLat());
        if (isgcj02) {
            llA = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());//Utils GPS to 火星坐标
        }

        BoundingBox bb = mapView.getBoundingBox();//获取当前区域
        //double[] regions = {_maxLon, _maxLat, _minLon, _minLat};
        double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};

        if (llA.GetLon() > regions[0] || llA.GetLat() > regions[1]
                || llA.GetLon() < regions[2] || llA.GetLat() < regions[3]) {
            return;
        }

        //经纬度坐标到屏幕坐标的转换
        Point A = new Point();
        Point e = new Point();
        mapView.getProjection().toProjectedPixels(llA.GetLat(),
                llA.GetLon(), A);
        Projection pj = mapView.getProjection();
        pj.toPixelsFromProjected(A, e);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        if (SysUtils.getInstance().is240x320) {
            paint.setTextSize(16);
        } else {
            paint.setFakeBoldText(true);
            paint.setStrokeWidth(2);
            paint.setTextSize(40);
        }
        paint.setTypeface(AppContext.getInstances().getIconfont());
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        float range = (float) (paomao_range / TileSystem.GroundResolution(llA.GetLat(), mapView.getZoomLevel()));

        paint.setColor(Color.parseColor("#A066FC66"));
        canvas.drawCircle(e.x, e.y, range, paint);

        paint.setColor(Color.parseColor("#FFFF0000"));
        String iconT = context.getString(R.string.fonticon_more_paomao);
        Rect rect = new Rect();
        paint.getTextBounds(iconT, 0, 1, rect);
        canvas.drawText(iconT, e.x - rect.width() / 2, e.y, paint);

    }

    public void draw3(Context context, org.mapsforge.core.graphics.Canvas canvas, org.mapsforge.core.model.BoundingBox bb, byte zoomLevel, org.mapsforge.core.model.Point topLeftPoint, DisplayModel displayModel) {
        if (mContext == null) {
            mContext = context;
        }
        if (!paomao_used || ll == null || ll.IsInvalid()) {
            return;
        }

        LonLat llA = new LonLat(ll.GetLon(), ll.GetLat());

        android.graphics.Canvas androidCanvas = AndroidGraphicFactory.getCanvas(canvas);

        double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};

        if (llA.GetLon() > regions[0] || llA.GetLat() > regions[1]
                || llA.GetLon() < regions[2] || llA.GetLat() < regions[3]) {
            return;
        }

        //经纬度坐标到屏幕坐标的转换
        long mapSize = MercatorProjection.getMapSize(zoomLevel, displayModel.getTileSize());
        int x = (int) (MercatorProjection.longitudeToPixelX(llA.GetLon(), mapSize) - topLeftPoint.x);
        int y = (int) (MercatorProjection.latitudeToPixelY(llA.GetLat(), mapSize) - topLeftPoint.y);
        Point e = new Point(x, y);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        if (SysUtils.getInstance().is240x320) {
            paint.setTextSize(16);
        } else {
            paint.setFakeBoldText(true);
            paint.setStrokeWidth(2);
            paint.setTextSize(40);
        }
        paint.setTypeface(AppContext.getInstances().getIconfont());
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        float range = (float) (paomao_range / TileSystem.GroundResolution(llA.GetLat(), zoomLevel));

        paint.setColor(Color.parseColor("#A066FC66"));
        androidCanvas.drawCircle(e.x, e.y, range, paint);

        paint.setColor(Color.parseColor("#FFFF0000"));
        String iconT = context.getString(R.string.fonticon_more_paomao);
        Rect rect = new Rect();
        paint.getTextBounds(iconT, 0, 1, rect);
        androidCanvas.drawText(iconT, e.x - rect.width() / 2, e.y, paint);

    }
}
